let currentTask = false; // 当前任务空闲标志
const taskQueue = []; // 任务队列
const THREAD_COUNT = navigator.hardwareConcurrency || 4; // 默认线程基数

/**
 * 处理线程任务
 *
 * @param {File} file
 * @param {Number} batchIndex 批次索引
 * @returns
 */
const hanldeThreadTask = ({ onProgress, ...props }) => {
  return new Promise((resolve) => {
    const result = []; // 线程处理结果
    let finishCount = 0; // 完成任务计数

    let progress = 0;
    const handleProgress = () => {
      progress += 100 / THREAD_COUNT;
      onProgress && onProgress(Math.floor(progress), THREAD_COUNT);
    };

    for (let index = 0; index < THREAD_COUNT; index++) {
      // 创建线程
      const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
      // 发送线程消息
      worker.postMessage({
        threadIndex: index,
        threadCount: THREAD_COUNT,
        ...props,
      });

      // eslint-disable-next-line no-loop-func
      worker.onmessage = (e) => {
        result[index] = e.data; // 保存线程处理结果
        worker.terminate(); // 结束线程
        handleProgress(); // 进度回调
        // 返回结果
        ++finishCount === THREAD_COUNT && resolve(result.flat());
      };
    }
  });
};

/**
 * 线程任务函数
 *
 * @param {File} file
 * @param {Number} batchIndex 批次索引
 * @returns 线程处理完成结果
 */
const threadTask = (props) => {
  return new Promise((resolve, reject) => {
    if (currentTask === false) {
      currentTask = true;
      return hanldeThreadTask(props)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
        .finally(() => {
          currentTask = false;
          const nextTaskQueue = taskQueue.shift();
          nextTaskQueue && nextTaskQueue();
        });
    }
    taskQueue.push(() => resolve(threadTask(props)));
  });
};

export default threadTask;
